package com.itheima.dubbo.filter;



import cn.hutool.core.util.StrUtil;
import com.itheima.dubbo.utils.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sun.security.provider.certpath.OCSPResponse;

import java.net.URI;

//设置网管过滤器：安全校验
//加入到aop容器中
@Component
public class GlobalGateFilter implements GlobalFilter {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //安全校验
        //不需要校验token的请求，。。。。。
        String uri = exchange.getRequest().getURI().getPath();
        //todo 暴漏接口
        if (StrUtil.equals(uri, "/user/login") || StrUtil.equals(uri, "/user/loginVerification"))
            return chain.filter(exchange);

        //1.校验token基于远端调用,
        // 1.1得到用户id
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        Long uid = restTemplate.getForObject("http://localhost:18080/user/" + token, Long.class);
        // 1.2判断token时效
        if (uid != null) {
            //todo 将用户id存入到redis中
            stringRedisTemplate.opsForValue().set("UID", uid+"");
            return chain.filter(exchange);
        }


        //1.1从exchang中获得我们所需要的数据
      /*  String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        //1.2由于网关不能加入web依赖，所以将工具类加入到模块中,-1,0代表token有效
        if (AppJwtUtil.verifyToken(AppJwtUtil.getClaimsBody(token)) == -1 || AppJwtUtil.verifyToken(AppJwtUtil.getClaimsBody(token)) == 0)
            //1.3有效放行
            return chain.filter(exchange);*/
        //1.(第二种方法)通过远端调用

        //未认证返回401
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();


    }
}
